package com.ciwong.epaper.modules.cordva;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.share.WxShareHelper;
import com.ciwong.epaper.modules.share.WxShareListener;
import com.ciwong.epaper.modules.share.bean.ShareMsgObj;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.ConfigXmlParser;
import org.apache.cordova.CordovaInterfaceImpl;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewImpl;
import org.apache.cordova.engine.SystemWebChromeClient;
import org.apache.cordova.engine.SystemWebView;
import org.apache.cordova.engine.SystemWebViewClient;
import org.apache.cordova.engine.SystemWebViewEngine;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * Created by young on 2016/10/18.
 * h5 页面基础类  所有与H5相关页面都需要继承这个类
 */
public abstract class BaseHtmlActicity extends BaseActivity implements SystemWebViewClient.LoadCallback, GoBackListener {
    public static final String TAG = "BaseHtmlActicity";

    protected CordovaWebView cordovaWebView;
    public final ArrayBlockingQueue<String> onPageFinishedUrl = new ArrayBlockingQueue<String>(5);
    protected StringBuffer startURL;
    //用于加载的webView
    public SystemWebView webView;
    private ImageButton duiba_close;

    //无网时提示信息
    protected ViewGroup no_net_work;
    protected Button try_again;

    protected int doWorkType;

    private String currentTitle;
    TextView textView;
    private String currentUrl;

    private Context mContext;

    public String wx_text;


    protected CordovaInterfaceImpl cordovaInterface = new CordovaInterfaceImpl(this) {
        @Override
        public Object onMessage(String id, Object data) {
            //影响在线加载，屏蔽掉
            if ("onPageFinished".equals(id)) {
                try {
                    onPageFinishedUrl.add((String) data);

                } catch (IllegalStateException e) {

                }
            }
            return super.onMessage(id, data);
        }
    };
    protected SystemWebViewEngine systemWebViewEngine;

    public CordovaWebView getCordovaWebView() {
        return cordovaWebView;
    }

    //发送回调
    protected void sendCallBack(String callbackId, String msg) {
        //        if (!callbackId.isEmpty()  )
        if (!TextUtils.isEmpty(callbackId) && !TextUtils.isEmpty(msg)) {
            CallbackContext callbackContext = new CallbackContext(callbackId, cordovaWebView);
            callbackContext.success(msg);
        }
    }

    //发送回调
    protected void sendCallBackInt(String callbackId, int msg) {
        if (!callbackId.isEmpty()) {
            CallbackContext callbackContext = new CallbackContext(callbackId, cordovaWebView);
            callbackContext.success(msg);
        }
    }


    public void setStartURL(String url) {
        String handleUrl = handleURL(url);
        this.startURL = new StringBuffer(handleUrl);
    }

    @Override
    protected int setView() {
        return R.layout.htmlactivity;
    }

    protected void loadUrl(String url) {
        String handleUrl = handleURL(url);
        if (TextUtils.isEmpty(handleUrl))
            handleUrl = startURL.toString();
        if (TextUtils.isEmpty(handleUrl)) {
            toastInCenter("错误：路径不存在!");
            return;
        }
        currentUrl = handleUrl;
        webView.loadUrl(handleUrl);
    }

    private String handleURL(String url) {
        if (!TextUtils.isEmpty(url))
            if (!url.contains("http") && !url.contains("file://"))//解决连接中不包含http 导致闪退的bug
                url = "http://" + url;
        return url;
    }

    @Override
    protected void findViews() {

        try {
            webView = findViewById(R.id.cordovaWebView);
            WebSettings webSettings = webView.getSettings();
            webSettings.setSavePassword(false);
            webSettings.setBuiltInZoomControls(false);// 设置是否显示缩放按钮
            webSettings.setDomStorageEnabled(true); // 支持缩放
            webSettings.setTextZoom(EApplication.getInstance().gettextZoom());
            //android 11 上面google出于安全考虑，不推荐用webview直接访问文件，如果实际项目中有需要，就需要设置为true
            webSettings.setAllowFileAccess(true);
            textView = findViewById(R.id.duiba_title_tv);
            duiba_close = findViewById(R.id.duiba_back);
            if (Build.VERSION.SDK_INT >= 21) {//解决webview白板问题
                webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }
            no_net_work = (ViewGroup) findViewById(R.id.ll_no_net);
            try_again = (Button) findViewById(R.id.btn_retry);
//            webView.goBack();
        } catch (RuntimeException e) {
            e.printStackTrace();
        }

    }


    @Override
    protected void initEvent() {

    }

    @Override
    protected void init() {
        try {
            setValideSource(false);

            mContext = this;

            //初始化cordovaWebView
            systemWebViewEngine = new SystemWebViewEngine(webView);

            cordovaWebView = new CordovaWebViewImpl(systemWebViewEngine);
            //Set up the webview
            ConfigXmlParser parser = new ConfigXmlParser();
            parser.parse(this);
            cordovaWebView.init(this, cordovaInterface, parser.getPluginEntries(), parser.getPreferences());

            SystemWebViewClient systemWebViewClient = new SystemWebViewClient(systemWebViewEngine) {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if (url.contains("ciwong.com") || url.contains("jiaofuyun.com") || url.contains("edu.cn")
                            || url.contains("smartedu.cn") || url.contains("moe.gov.cn") || url.contains("eduyun.cn")
                            || url.contains("xuetangx.com") || url.contains("zhihuishu.com") || url.contains("chsi.com.cn")
                            || url.contains("icourse163.org") || url.contains("gtaskillc.com") || url.contains("icve.com.cn")
                            || url.contains("ehuixue.cn") || url.contains("xueyinonline.com") || url.contains("tbook.com.cn")
                            || url.contains("chinaooc.com.cn") || url.contains("neea.cn") || url.contains("nvic.com.cn")
                            || url.contains("ttcdw.cn")) {
                        if (url.contains("https://x-link.ykt.eduyun.cn/smart_links/")) {
                            ToastUtil.INSTANCE.toastCenter(BaseHtmlActicity.this, "此网站不在安全网站名单中。。。", Toast.LENGTH_LONG, -1);
                            return true;
                        }
                    } else {
                        CWLog.i("byou", "此网站不在安全网站名单中:startURL=" + url);
                        ToastUtil.INSTANCE.toastCenter(BaseHtmlActicity.this, "此网站不在安全网站名单中。。。", Toast.LENGTH_LONG, -1);
                        return true;
                    }
                    WebView.HitTestResult hitTestResult = view.getHitTestResult();
                    //WebView hitTestResult==null解决重定向问题
                    if (!TextUtils.isEmpty(url) && hitTestResult == null) {
                        view.loadUrl(url);
                        return true;
                    }
                    currentUrl = url;
                    return super.shouldOverrideUrlLoading(view, url);
                }

                @Override
                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                    super.onReceivedError(view, errorCode, description, failingUrl);
                    webViewError();
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    if (webView.canGoBack()) {
                        setBackImg(R.mipmap.nav_btn_return_left);
                        if (null != duiba_close) {
                            duiba_close.setVisibility(View.VISIBLE);
                        }

                    } else {
                        if (null != duiba_close) {
                            duiba_close.setVisibility(View.GONE);
                        }
                    }

                }

            };
            SystemWebChromeClient systemWebChromeClient = new SystemWebChromeClient(systemWebViewEngine) {
                @Override
                public void onReceivedTitle(WebView view, String title) {//监听标题改变
                    boolean isOnline = true;
                    try {
                        isOnline = NetworkUtils.isOnline();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (isOnline && !TextUtils.isEmpty(title)) {
                        currentTitle = title;
                        String tag = "";
                        if (doWorkType == 1) {
                            tag = "订正错题  ";
                        }
                        setTitleText(tag + title);
                        if (null != textView) {
                            textView.setText(currentTitle);
                        }
                        //System.out.println("网页的标题title为 ："+title);
                        if (!webpageException(title)) {
                            webViewError();
                        } else {
                            webView.setVisibility(View.VISIBLE);
                            no_net_work.setVisibility(View.GONE);
                        }
                        if (currentTitle.equals("配音详情")) {
                            showShareUrlBtn();
                        }
                    }
                }
            };
            webView.setWebViewClient(systemWebViewClient);
            webView.setWebChromeClient(systemWebChromeClient);

            try_again.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean isOnline = true;
                    try {
                        isOnline = NetworkUtils.isOnline();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (isOnline) {
                        if (!webpageException(currentTitle)) {
                            webView.setVisibility(View.GONE);
                        } else {
                            webView.setVisibility(View.VISIBLE);
                        }
                        //重新加载网页
                        webView.loadUrl(startURL.toString());
                        no_net_work.setVisibility(View.GONE);
                    }
                }
            });
        } catch (Exception e) {

        }
    }

    /**
     * 显示分享图标
     */
    private void showShareUrlBtn() {
        showRightBtn();
        setImgRightBtn(R.mipmap.ic_share);
        setImgRightBtnListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {
                //currentUrl
                weChatShare(1);//微信朋友分享
            }
        });
    }


    /**
     * 1代表分享给好友，2代表分享到朋友圈
     *
     * @param wxType
     */
    private void weChatShare(int wxType) {
        WxShareHelper.getInstance().initWxShare(BaseHtmlActicity.this, new WxShareListener() {
            @Override
            public void onWxShareing(String str) {
                ToastUtil.INSTANCE.toastInCenter(mContext, "分享中...");
            }

            @Override
            public void onWxShareSucc(String var) {
                ToastUtil.INSTANCE.toastCenterSuccess("分享成功");
            }

            @Override
            public void onWxShareFailure(int var, String var1) {
                ToastUtil.INSTANCE.toastCenterError("分享失败");

            }

            @Override
            public boolean onWxShareCancel() {
                ToastUtil.INSTANCE.toastCenter(mContext, "取消分享", R.mipmap.ic_cancel);

                return false;
            }
        });
        ShareMsgObj shareMsgObj = new ShareMsgObj();
        shareMsgObj.setWxType(wxType);//类型：微信朋友1，微信朋友圈2
        shareMsgObj.setShareType(ShareMsgObj.ShareType.SHARE_WEB);
        //        shareMsgObj.setMsgTitle(mTitleText);

        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.lsw_wx_share);
        shareMsgObj.setThunbBmp(bmp);
        if (null != currentUrl && !"".equals(currentUrl)) {
            shareMsgObj.setUrl(currentUrl + "&noAlert=1");
        } else {
            shareMsgObj.setUrl(startURL + "&noAlert=1");
        }

        String shareContent;
        String score = getUserInfoBase().getRealName();
        shareContent = getString(R.string.str_share_py, score);
        if (wxType == 1) {
            shareMsgObj.setMsgTitle(shareContent);
            if (null != wx_text && !"".equals(wx_text)) {
                shareMsgObj.setMsgDesription(wx_text);
            }
        } else if (wxType == 2) {
            shareMsgObj.setMsgDesription(currentTitle);
        }
        WxShareHelper.getInstance().sendReq(shareMsgObj);
    }


    /**
     * 通过标题判断网页是否异常
     *
     * @param title 标题
     * @return true 表示网页正常情况，false表示网页异常
     */
    private boolean webpageException(String title) {
        if (title == null) return true;
        if (title.contains("网页")) {
            if (title.contains("找不到") || title.contains("无法打开")
                    || title.contains("错误") || title.contains("异常"))
                return false;
        }
        return true;
    }

    private void webViewError() {
        if (webView != null && no_net_work != null) {
            webView.setVisibility(View.GONE);
            no_net_work.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.destroy();
            webView.setVisibility(View.GONE);
        }
        if (cordovaWebView != null) {
            cordovaWebView.getEngine().destroy();
            cordovaWebView.getPluginManager().onDestroy();
            cordovaWebView = null;
        }
        super.onDestroy();
    }


    @Override
    protected void loadData() {
        showNetErrorWork(getResources().getString(R.string.get_errorresing_info));
    }

    @Override
    public void onLoadOver() {

    }

    @Override
    public void onBackFinish() {
        System.out.println("返回键点击了");

    }

    /**
     * 无网络环境下的时候，显示提醒页面
     */
    protected void showNetErrorWork(String noNetTip) {
        if (!NetworkUtils.isOnline()) {
            if (webView != null)
                webView.setVisibility(View.GONE);
            if (no_net_work != null)
                no_net_work.setVisibility(View.VISIBLE);
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void goBack() {
        if (webView != null && webView.canGoBack()) {
            webView.goBack();
        } else {
            finish();
        }
    }

    public void finishActivity() {
        super.finish();
    }

    @Override
    public void finish() {
        super.finish();
//注掉下面代码解决 h5页面返回时有空白页面
        /*runOnUiThread(new Runnable() {
            @Override
            public void run() {

                ViewGroup view = (ViewGroup) getWindow().getDecorView();
                view.setBackgroundColor(getResources().getColor(R.color.white));
                for (int i = 0; i < view.getChildCount(); i++) {
                    if (view.getChildAt(i).getParent() != null) {
                        view.removeView(view.getChildAt(i));
                    }
                }
                BaseHtmlActicity.super.finish();

            }
        });*/

    }
}
